package jp.cane.android.luciferblue;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;

public class MainThread implements Runnable {
	private MainService service = null;

	private BluetoothAdapter adapter = null;
	private BluetoothSocket socket = null;

	private Thread thread = null;
	private String log = "";

	protected Calendar lastReceivedTime = Calendar.getInstance();
	protected long totalCount = -1;
	protected ArrayList<Long> countList = new ArrayList<Long>();

	public MainThread(MainService service) {
		this.service = service;

		adapter = BluetoothAdapter.getDefaultAdapter();

		if (this.thread == null) {
			this.thread = new Thread(this);
			this.thread.start();
		}
	}

	public void destroy() {
		closeSocket();
		if (this.thread != null && this.thread.isAlive()) {
			this.thread.interrupt();
			this.thread = null;
		}
	}

	public String getLog() {
		return this.log;
	}

	private synchronized void append(String str) {
		String strs[] = this.log.split("\n");
		String strtext = str + "<br />\n";
		for (int i = 0; i < strs.length && i < 50; i++) {
			strtext += strs[i] + "\n";
		}
		this.log = strtext;
	}

	public void run() {
		while (true) {
			try {
				BluetoothDevice device = MainService.device;
				append("device: " + device);
				if (device == null) {
					BluetoothServerSocket ssocket = null;
					try {
						ssocket = adapter.listenUsingRfcommWithServiceRecord(
								"luciferblue",
								BluetoothProtocols.SERIAL_PORT_PROTOCOL_UUID);
						socket = ssocket.accept();
					} finally {
						if (ssocket != null) {
							ssocket.close();
						}
					}
				} else {
					socket = device
							.createInsecureRfcommSocketToServiceRecord(BluetoothProtocols.SERIAL_PORT_PROTOCOL_UUID);
					socket.connect();
				}
				append("Connected");

				BufferedReader reader = new BufferedReader(
						new InputStreamReader(new BufferedInputStream(
								socket.getInputStream())));
				while (true) {
					final String prefix = "COUNT:";
					long lastCount = totalCount;
					String line = reader.readLine();
					lastReceivedTime = Calendar.getInstance();
					if (line == null) {
						break;
					}
					line = line.replaceAll("\0", "");
					if (line.startsWith(prefix)) {
						String number = line.substring(prefix.length());
						totalCount = Long.valueOf(number);
					}
					if (lastCount < 0 || lastCount > totalCount) {
						lastCount = totalCount;
						countList.clear();
						MainService.sn = 0;
					}
					for (int i = 0; i < totalCount - lastCount; i++) {
						countList.add(Long.valueOf(System.currentTimeMillis()));
					}
					// String tmp = "";
					// for (byte a : line.getBytes()) {
					// tmp += " " + (int) a;
					// }
					// line = tmp;
					this.service.change(line);
					append("<font color='red'>" + line + "</font>");
				}
				// } catch (InterruptedException e) {
				// closeSocket();
				// append("Closed.");
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				closeSocket();
				append("Closed.");
			}
		}
	}

	protected void send(String str, boolean echo) {
		if (socket != null) {
			try {
				BufferedOutputStream os = new BufferedOutputStream(
						socket.getOutputStream());
				os.write((str + "\n").getBytes());
				os.flush();
				if (echo) {
					append("<font color='blue'>" + str + "</font>");
				}
			} catch (IOException e) {
			}
		}
	}

	private void closeSocket() {
		try {
			socket.close();
		} catch (Exception e) {
		}
		socket = null;
	}
}
